<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Workerman\Worker;
use \GatewayWorker\Lib\Gateway;
require_once 'vendor/autoload.php';
// 初始化一个worker容器，监听1234端口
$worker = new Worker('tcp://0.0.0.0:2700');

class Socket1 extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model("User_model");
		$this->load->model("Device_model");
		$this->load->helper('url');
	}

	public function index()
	{
		global $worker;
		// 新增加一个属性，用来保存uid到connection的映射
		$worker->uidConnections = array();

		// worker进程启动后创建一个text Worker以便打开一个内部通讯端口
		$worker->onWorkerStart = function($worker)
		{
			//开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
			$inner_text_worker = new Worker('text://0.0.0.0:2701');
			$inner_text_worker->onMessage = function($connection, $data)
			{
				// $data数组格式，里面有uid，表示向那个uid的页面推送数据
				$param = json_decode($data, true);
				$deviceId = $param['deviceId'];
				// 通过workerman，向uid的页面推送数据
				$ret = $this->sendMessageByUid($deviceId, $data);
				// 返回推送结果
				$connection->send($ret ? 'ok' : 'fail');
			};
			// ## 执行监听 ##
			$inner_text_worker->listen();
		};

		//当连接建立时触发
		$worker->onConnect = function($connection)
		{
			$connection->send('hello,this is vic!Connect success!congratulations :)');
//			echo "new connection from ip " . $connection->getRemoteIp() . "\n";
		};

		// 当有客户端发来消息时执行的回调函数
		$worker->onMessage = function($connection, $data)
		{
			global $worker;
			// 判断当前客户端是否已经验证,既是否设置了uid
			if(!isset($connection->uid))
			{
				// 没验证的话把第一个包当做uid（这里为了方便演示，没做真正的验证）
//				$connection->uid = $data;
//				/* 保存uid到connection的映射，这样可以方便的通过uid查找connection，
//                 * 实现针对特定uid推送数据
//                 */
//				$worker->uidConnections[$connection->uid] = $connection;
//				$connection->send(var_dump($connection->uid));
				$data = '{"deviceId":"09BB7e7tfhwixAvq8lWniawQTlpRDLWc"}';
				$param = json_decode($data,true);
				if(empty($param['deviceId'])){
					$connection->close("device id can not be null!");
					return;
				}
				$deviceInfo = $this->Device_model->getDeviceInfo($param['deviceId']);
				$worker->uidConnections[$param['deviceId']] = $connection;
				$connection->send('车途宝已准备就绪...');

				return;
			}
		};

		// 当有客户端连接断开时
		$worker->onClose = function($connection)
		{
			global $worker;
			if(isset($connection->uid))
			{
				// 连接断开时删除映射
				unset($worker->uidConnections[$connection->uid]);
			}
		};

		// 运行worker
		Worker::runAll();
	}

	// 向所有验证的用户推送数据
	function broadcast($message)
	{
		global $worker;
		foreach($worker->uidConnections as $connection)
		{
			$connection->send($message);
		}
	}

// 针对uid推送数据
	function sendMessageByUid($uid, $message)
	{
		global $worker;
		if(isset($worker->uidConnections[$uid]))
		{
			$connection = $worker->uidConnections[$uid];
			$connection->send($message);
			return true;
		}
		return false;
	}
}
